package cn.stylefeng.guns.modular.basic.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.stylefeng.guns.modular.basic.model.params.BasicCustomerParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.ExcelWrite;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.mapper.BasicPutgoodsMapper;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicLineParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicLineResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicAddressService;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicLineService;
import  cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicUnitCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsCodeResult;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicUnitCodeResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicUnitCodeService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.params.DictParam;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 收货单位表 服务实现类
 */
@Service
public class BasicPutgoodsServiceImpl extends ServiceImpl<BasicPutgoodsMapper, BasicPutgoods> implements BasicPutgoodsService {

    @Override
    public void add(BasicPutgoodsParam param){
        BasicPutgoods entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BasicPutgoodsParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BasicPutgoodsParam param){
        BasicPutgoods oldEntity = getOldEntity(param);
        BasicPutgoods newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BasicPutgoodsResult findBySpec(BasicPutgoodsParam param, Long operateId){
        return this.baseMapper.findBySpec(param, operateId);
    }

    @Override
    public List<BasicPutgoodsResult> findListBySpec(BasicPutgoodsParam param, Long operateId){
        return this.baseMapper.findListBySpec(param, operateId);
    }

    @Override
    public LayuiPageInfo findPageBySpecHx(BasicPutgoodsParam param,String condition,Long deptId, Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findPageBySpecHx(pageContext, param,condition,deptId,operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<BasicPutgoodsResult> findAvailableList(Long deptId, Long deliverId, Long operateId) {
        BasicPutgoods param = new BasicPutgoods();
        param.setDeptId(deptId);
        param.setDeliverId(deliverId);
        return this.baseMapper.findListBySpec1(param,operateId);
    }

    @Override
    public LayuiPageInfo findPageBySpec(BasicPutgoodsParam param,String condition,Long deptId, Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition,deptId,operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo findPageNewBySpec(BasicPutgoodsParam param,String condition,Long deptId, Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.findPageNewBySpec(pageContext, param,condition,deptId,operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(BasicPutgoodsParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BasicPutgoods getOldEntity(BasicPutgoodsParam param) {
        return this.getById(getKey(param));
    }

    private BasicPutgoods getEntity(BasicPutgoodsParam param) {
        BasicPutgoods entity = new BasicPutgoods();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    
	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }
	
	@Resource
	BasicCustomerService basicCustomerService;
	
	@Resource
    private BasicAddressService basicAddressService;

	@Resource
    private BasicLineService basicLineService;
	
	@Resource
    private UserService userService;

	@Resource
    private DictService dictService;

	@Resource
    private HxBasicUnitCodeService hxBasicUnitCodeService;

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData getExceldatahx(MultipartFile file, BasicPutgoodsParam basicPutgoodsParam, ResponseData data) throws IOException {
		User user = userService.getcurrentUser();
		basicPutgoodsParam.setDeliverId(user.getDeliverId());
		basicPutgoodsParam.setDeptId(user.getDeptId());
		if (basicPutgoodsParam.getPutgoodsCustomerId() == null) {
			data.setSuccess(false);
			data.setMessage("Please Select Customer");
			return data;
		}
		BasicCustomer basicCustomer = basicCustomerService.getById(basicPutgoodsParam.getPutgoodsCustomerId());
		String fileName = file.getOriginalFilename();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Upload file format is incorrect");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            BasicPutgoods bd = new BasicPutgoods();
            BasicAddressParam bd2 = new BasicAddressParam();
            bd.setDeliverId(basicPutgoodsParam.getDeliverId());
            bd.setDeptId(basicPutgoodsParam.getDeptId());
            bd.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
            bd.setPutgoodsOperateName(basicCustomer.getCustomerName());
            
            String  putgoodsName = getCellValue(row.getCell(2));//单位名称
            if (ToolUtil.isNotEmpty(putgoodsName)) {
            	bd.setPutgoodsName(putgoodsName);
            	bd2.setPutgoodsName(putgoodsName);
			} else {
			data.setSuccess(false);
			data.setMessage("Unit name cannot be empty");
			return data;
		}
			BasicPutgoods basicPutgoods = this.lambdaQuery()
			.eq(BasicPutgoods::getPutgoodsName, putgoodsName)
			.eq(BasicPutgoods::getPutgoodsCustomerId, basicPutgoodsParam.getPutgoodsCustomerId())
			.last("LIMIT 1")
			.one();
            if (basicPutgoods == null) {
                String  unitNumber = getCellValue(row.getCell(3));//单位编号
                if (ToolUtil.isNotEmpty(unitNumber)) {
                	bd.setUnitNumber(unitNumber);
    			} 
                
                String  unitType = getCellValue(row.getCell(0));//单位类型
                if (ToolUtil.isNotEmpty(unitType)) {
                	bd.setUnitType(unitType);
                	if(!unitType.equals("门店")&&!unitType.equals("供应商")&&!unitType.equals("批发客户")&&!unitType.equals("配送中心")) {
        				data.setSuccess(false);
        				data.setMessage("Unit type error");
        				return data;
                	}
    			} else {
    				data.setSuccess(false);
    				data.setMessage("Unit type cannot be empty");
    				return data;
    			}
                
                String  fenlei = getCellValue(row.getCell(1));//分类
                if (ToolUtil.isNotEmpty(fenlei)) {
                	HxBasicUnitCodeParam codeParam = new HxBasicUnitCodeParam();
                	codeParam.setDeptId(basicPutgoodsParam.getDeptId());
                	codeParam.setDeliverId(basicPutgoodsParam.getDeliverId());
                	codeParam.setCodeName(fenlei);
                	codeParam.setV1(bd.getUnitType());
                	codeParam.setOperateId(user.getOperateId());
                	HxBasicUnitCodeResult codeResult = hxBasicUnitCodeService.findBySpec(codeParam);
                	if(codeResult == null) {
        				data.setSuccess(false);
        				data.setMessage(fenlei+" group system does not exist, please contact administrator");
        				return data;
                	} else {
                		bd.setDictId(Long.parseLong(codeResult.getId().toString()));
                	}
    			} 
                
                String  sheng = getCellValue(row.getCell(4));
                if (ToolUtil.isNotEmpty(sheng)) {
                	bd2.setSheng(sheng);
    			} 
                
                String  shi = getCellValue(row.getCell(5));
                if (ToolUtil.isNotEmpty(shi)) {
                	bd2.setShi(shi);
    			} 
                
                String  qu = getCellValue(row.getCell(6));
                if (ToolUtil.isNotEmpty(qu)) {
                	bd2.setQu(qu);
    			} 
                
                String  putgoodsContacts = getCellValue(row.getCell(7));
                if (ToolUtil.isNotEmpty(putgoodsContacts)) {
                	bd2.setContacts(putgoodsContacts);
    			} 
                
                String  putgoodsTel = getCellValue(row.getCell(8));
                if (ToolUtil.isNotEmpty(putgoodsTel)) {
                	bd2.setTel(putgoodsTel);
    			} 
                
                String  putgoodsAddress = getCellValue(row.getCell(9));
                if (ToolUtil.isNotEmpty(putgoodsAddress)) {
                	bd2.setAddress(putgoodsAddress);
    			} else {
			data.setSuccess(false);
			data.setMessage("Detailed address cannot be empty");
			return data;
		}
                
                String  longitude = getCellValue(row.getCell(10));
                if (ToolUtil.isNotEmpty(longitude)) {
                	BigDecimal longitudeb = new BigDecimal(longitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLongitude(longitudeb.toString());
    			} 
                
                String  latitude = getCellValue(row.getCell(11));
                if (ToolUtil.isNotEmpty(latitude)) {
                	BigDecimal latitudeb = new BigDecimal(latitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLatitude(latitudeb.toString());
    			} 
                
                String  kilometer = getCellValue(row.getCell(12));
                if (ToolUtil.isNotEmpty(kilometer)) {
                	BigDecimal kilometerb = new BigDecimal(kilometer).setScale(1,BigDecimal.ROUND_DOWN);
                	bd2.setKilometer(kilometerb.toString());
    			} 
                
                String  lineName = getCellValue(row.getCell(13));
                if (ToolUtil.isNotEmpty(lineName)) {
                	BasicLineParam basicLineParam = new BasicLineParam();
                	basicLineParam.setDeptId(userService.getDeptId());;
                	basicLineParam.setLineName(lineName);
                	BasicLineResult basicLineResult =  basicLineService.findBySpec(basicLineParam,user.getOperateId());
                	if(basicLineResult != null) {
                		bd2.setLineId(Long.parseLong(basicLineResult.getId().toString()));
                		bd2.setLineName(basicLineResult.getLineName());
                	}
    			} 
                
                String  putgoodsNotes = getCellValue(row.getCell(14));
                if (ToolUtil.isNotEmpty(putgoodsNotes)) {
                	if(putgoodsNotes.length()>100) {
			data.setSuccess(false);
			data.setMessage("Notes cannot exceed 100 characters");
			return data;
                }
                	bd.setPutgoodsNotes(putgoodsNotes);
    			}

                String  stockPort = getCellValue(row.getCell(15));
                if (ToolUtil.isNotEmpty(stockPort)) {
                    bd.setStockPort(stockPort);
                }

                this.save(bd);
                
                bd2.setPutgoodsId(Long.parseLong(bd.getId().toString()));
                if(ToolUtil.isEmpty(bd2.getLongitude())) {
                	bd2.setLongitude("0");
                }
                if(ToolUtil.isEmpty(bd2.getLatitude())) {
                    bd2.setLatitude("0");
                }
                bd2.setSwitchWl("1");
                bd2.setSwitchBj("1500");
                bd2.setSwitchBj2("2000");
                basicAddressService.add(bd2);
			} else {
                String  unitType = getCellValue(row.getCell(0));
                if (ToolUtil.isNotEmpty(unitType)) {
                	bd.setUnitType(unitType);
    			} else {
    				data.setSuccess(false);
    				data.setMessage("Unit type cannot be empty");
    				return data;
    			}
                
                String  fenlei = getCellValue(row.getCell(1));
                if (ToolUtil.isNotEmpty(fenlei)) {
                	HxBasicUnitCodeParam codeParam = new HxBasicUnitCodeParam();
                	codeParam.setDeptId(basicPutgoodsParam.getDeptId());
                	codeParam.setDeliverId(basicPutgoodsParam.getDeliverId());
                	codeParam.setCodeName(fenlei);
                	codeParam.setV1(bd.getUnitType());
                	codeParam.setOperateId(user.getOperateId());
                	HxBasicUnitCodeResult codeResult = hxBasicUnitCodeService.findBySpec(codeParam);
                	if(codeResult == null) {
        				data.setSuccess(false);
        				data.setMessage(fenlei+"分组系统不存在，请联系管理员");
        				return data;
                	} else {
                		bd.setDictId(Long.parseLong(codeResult.getId().toString()));
                	}
    			} 
                
                String  sheng = getCellValue(row.getCell(4));
                if (ToolUtil.isNotEmpty(sheng)) {
                	bd2.setSheng(sheng);
    			} 
                
                String  shi = getCellValue(row.getCell(5));
                if (ToolUtil.isNotEmpty(shi)) {
                	bd2.setShi(shi);
    			} 
                
                String  qu = getCellValue(row.getCell(6));
                if (ToolUtil.isNotEmpty(qu)) {
                	bd2.setQu(qu);
    			} 
                
                String  putgoodsContacts = getCellValue(row.getCell(7));
                if (ToolUtil.isNotEmpty(putgoodsContacts)) {
                	bd2.setContacts(putgoodsContacts);
    			} 
                
                String  putgoodsTel = getCellValue(row.getCell(8));
                if (ToolUtil.isNotEmpty(putgoodsTel)) {
                	bd2.setTel(putgoodsTel);
    			} 
                
                String  putgoodsAddress = getCellValue(row.getCell(9));
                if (ToolUtil.isNotEmpty(putgoodsAddress)) {
                	bd2.setAddress(putgoodsAddress);
    			} else {
			data.setSuccess(false);
			data.setMessage("Detailed address cannot be empty");
			return data;
		}

                String  longitude = getCellValue(row.getCell(10));
                if (ToolUtil.isNotEmpty(longitude)) {
                	BigDecimal longitudeb = new BigDecimal(longitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLongitude(longitudeb.toString());
    			} 
                
                String  latitude = getCellValue(row.getCell(11));
                if (ToolUtil.isNotEmpty(latitude)) {
                	BigDecimal latitudeb = new BigDecimal(latitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLatitude(latitudeb.toString());
    			} 
                
                String  kilometer = getCellValue(row.getCell(12));
                if (ToolUtil.isNotEmpty(kilometer)) {
                	BigDecimal kilometerb = new BigDecimal(kilometer).setScale(1,BigDecimal.ROUND_DOWN);
                	bd2.setKilometer(kilometerb.toString());
    			} 
                
                String  lineName = getCellValue(row.getCell(13));
                if (ToolUtil.isNotEmpty(lineName)) {
                	BasicLineParam basicLineParam = new BasicLineParam();
                	basicLineParam.setDeptId(userService.getDeptId());
                	basicLineParam.setLineName(lineName);
                	BasicLineResult basicLineResult =  basicLineService.findBySpec(basicLineParam,user.getOperateId());
                	if(basicLineResult != null) {
                		bd2.setLineId(Long.parseLong(basicLineResult.getId().toString()));
                		bd2.setLineName(basicLineResult.getLineName());
                	}
    			} 
                
                String  putgoodsNotes = getCellValue(row.getCell(14));
                if (ToolUtil.isNotEmpty(putgoodsNotes)) {
                	if(putgoodsNotes.length()>100) {
			data.setSuccess(false);
			data.setMessage("Notes cannot exceed 100 characters");
			return data;
                }
                	bd.setPutgoodsNotes(putgoodsNotes);
    			} 
                
                bd.setId(basicPutgoods.getId());
                this.updateById(bd);
                
                bd2.setPutgoodsId(Long.parseLong(basicPutgoods.getId().toString()));
                BasicAddressResult addressResult = basicAddressService.findBySpec(bd2);
                if (addressResult == null) {
                    if(ToolUtil.isEmpty(bd2.getLongitude())) {
                    	bd2.setLongitude("0");
                    }
                    if(ToolUtil.isEmpty(bd2.getLatitude())) {
                        bd2.setLatitude("0");
                    }
                    bd2.setSwitchWl("1");
                    bd2.setSwitchBj("1500");
                    bd2.setSwitchBj2("2000");
                    basicAddressService.add(bd2);
				} else {
					bd2.setId(addressResult.getId());
					basicAddressService.update(bd2);
				}
			}
        }
		
        data.setSuccess(true);
		return data;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=280)
	public ResponseData getExceldata(MultipartFile file, BasicPutgoodsParam basicPutgoodsParam, ResponseData data) throws IOException {
		User user = userService.getcurrentUser();
		basicPutgoodsParam.setDeliverId(user.getDeliverId());
		basicPutgoodsParam.setDeptId(user.getDeptId());
		if (basicPutgoodsParam.getPutgoodsCustomerId() == null) {
			data.setSuccess(false);
			data.setMessage("Please Select Customer");
			return data;
		}
		BasicCustomer basicCustomer = basicCustomerService.getById(basicPutgoodsParam.getPutgoodsCustomerId());
		String fileName = file.getOriginalFilename();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Upload file format is incorrect");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);


		Map<String, BasicPutgoodsResult> putgoodsMap = new HashMap<>();
		BasicPutgoodsParam hxgoodsp = new BasicPutgoodsParam();
		hxgoodsp.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
		List<BasicPutgoodsResult> hxp = this.findListBySpec(hxgoodsp,null);
		for (BasicPutgoodsResult pr : hxp) {
			putgoodsMap.put(pr.getPutgoodsName(), pr);
		}
		
		Map<String, BasicLineResult> lineMap = new HashMap<>();
		BasicLineParam linep = new BasicLineParam();
		linep.setDeptId(user.getDeptId());
		List<BasicLineResult> lr = basicLineService.findListBySpec(linep,user.getOperateId());
		for (BasicLineResult pr : lr) {
			if(ToolUtil.isNotEmpty(pr.getLineName())) {
				lineMap.put(pr.getLineName(), pr);
			}
		}
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            BasicPutgoods bd = new BasicPutgoods();
            BasicAddressParam bd2 = new BasicAddressParam();
            bd.setDeliverId(basicPutgoodsParam.getDeliverId());
            bd.setDeptId(basicPutgoodsParam.getDeptId());
            bd.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
            bd.setPutgoodsOperateName(basicCustomer.getCustomerName());
            
            String  putgoodsName = getCellValue(row.getCell(0));//单位名称
            if (ToolUtil.isNotEmpty(putgoodsName)) {
            	bd.setPutgoodsName(putgoodsName);
            	bd2.setPutgoodsName(putgoodsName);
			} else {
			data.setSuccess(false);
			data.setMessage("Unit name cannot be empty");
			return data;
		}
            
            String  unitNumber = getCellValue(row.getCell(1));//单位编号
            if (ToolUtil.isNotEmpty(unitNumber)) {
            	bd.setUnitNumber(unitNumber);
			} 
            BasicPutgoodsResult  basicPutgoodsResult = putgoodsMap.get(putgoodsName);
            if (basicPutgoodsResult == null) {
                String  unitCategory = getCellValue(row.getCell(2));//单位类别
                if (ToolUtil.isNotEmpty(unitCategory)) {
                	bd.setUnitCategory(unitCategory);
    			} 
                
                String  unitType = getCellValue(row.getCell(3));//性质
                if (ToolUtil.isNotEmpty(unitType)) {
                	bd.setUnitType(unitType);
    			} 
                
                String  sheng = getCellValue(row.getCell(4));//省
                if (ToolUtil.isNotEmpty(sheng)) {
                	bd2.setSheng(sheng);
    			} 
                
                String  shi = getCellValue(row.getCell(5));//市
                if (ToolUtil.isNotEmpty(shi)) {
                	bd2.setShi(shi);
    			} 
                
                String  qu = getCellValue(row.getCell(6));//区
                if (ToolUtil.isNotEmpty(qu)) {
                	bd2.setQu(qu);
    			} 
                
                String  putgoodsContacts = getCellValue(row.getCell(7));
                if (ToolUtil.isNotEmpty(putgoodsContacts)) {
                	bd2.setContacts(putgoodsContacts);
    			} 
                
                String  putgoodsTel = getCellValue(row.getCell(8));
                if (ToolUtil.isNotEmpty(putgoodsTel)) {
                	bd2.setTel(putgoodsTel);
    			} 
                
                String  putgoodsAddress = getCellValue(row.getCell(9));
                if (ToolUtil.isNotEmpty(putgoodsAddress)) {
                	bd2.setAddress(putgoodsAddress);
    			} else {
                	bd2.setAddress(putgoodsName);
			data.setSuccess(false);
			data.setMessage("Detailed address cannot be empty");
			return data;
		}

                String  longitude = getCellValue(row.getCell(10));
                if (ToolUtil.isNotEmpty(longitude)) {
                	BigDecimal longitudeb = new BigDecimal(longitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLongitude(longitudeb.toString());
    			} 
                
                String  latitude = getCellValue(row.getCell(11));
                if (ToolUtil.isNotEmpty(latitude)) {
                	BigDecimal latitudeb = new BigDecimal(latitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLatitude(latitudeb.toString());
    			} 
                
                String  kilometer = getCellValue(row.getCell(12));
                if (ToolUtil.isNotEmpty(kilometer)) {
                	BigDecimal kilometerb = new BigDecimal(kilometer).setScale(1,BigDecimal.ROUND_DOWN);
                	bd2.setKilometer(kilometerb.toString());
    			} 
                
                String  lineName = getCellValue(row.getCell(13));
                if (ToolUtil.isNotEmpty(lineName)) {
                	BasicLineResult  basicLineResult = lineMap.get(lineName);
                	if(basicLineResult != null) {
                		bd2.setLineId(Long.parseLong(basicLineResult.getId().toString()));
                		bd2.setLineName(basicLineResult.getLineName());
                	}
    			} 
                
                String  putgoodsNotes = getCellValue(row.getCell(14));
                if (ToolUtil.isNotEmpty(putgoodsNotes)) {
                	if(putgoodsNotes.length()>100) {
        				data.setSuccess(false);
        				data.setMessage("Notes cannot exceed 100 characters");
        				return data;
                	}
                	bd.setPutgoodsNotes(putgoodsNotes);
    			} 
                
                this.save(bd);
                
                bd2.setPutgoodsId(Long.parseLong(bd.getId().toString()));
                if(ToolUtil.isEmpty(bd2.getLongitude())) {
                	bd2.setLongitude("0");
                }
                if(ToolUtil.isEmpty(bd2.getLatitude())) {
                    bd2.setLatitude("0");
                }
                bd2.setSwitchWl("1");
                bd2.setSwitchBj("1500");
                bd2.setSwitchBj2("2000");
                basicAddressService.add(bd2);
			} else {
                String  unitCategory = getCellValue(row.getCell(2));//单位类别
                if (ToolUtil.isNotEmpty(unitCategory)) {
                	bd.setUnitCategory(unitCategory);
    			} 
                
                String  unitType = getCellValue(row.getCell(3));//单位性质
                if (ToolUtil.isNotEmpty(unitType)) {
                	bd.setUnitType(unitType);
    			} 
                
                String  sheng = getCellValue(row.getCell(4));//省
                if (ToolUtil.isNotEmpty(sheng)) {
                	bd2.setSheng(sheng);
    			} 
                
                String  shi = getCellValue(row.getCell(5));//市
                if (ToolUtil.isNotEmpty(shi)) {
                	bd2.setShi(shi);
    			} 
                
                String  qu = getCellValue(row.getCell(6));//区
                if (ToolUtil.isNotEmpty(qu)) {
                	bd2.setQu(qu);
    			} 
                
                String  putgoodsContacts = getCellValue(row.getCell(7));
                if (ToolUtil.isNotEmpty(putgoodsContacts)) {
                	bd2.setContacts(putgoodsContacts);
    			} 
                
                String  putgoodsTel = getCellValue(row.getCell(8));
                if (ToolUtil.isNotEmpty(putgoodsTel)) {
                	bd2.setTel(putgoodsTel);
    			} 
                
                String  putgoodsAddress = getCellValue(row.getCell(9));
                if (ToolUtil.isNotEmpty(putgoodsAddress)) {
                	bd2.setAddress(putgoodsAddress);
    			} else {
    				data.setSuccess(false);
    				data.setMessage("详细地址不得为空");
    				return data;
    			}
                
                String  longitude = getCellValue(row.getCell(10));
                if (ToolUtil.isNotEmpty(longitude)) {
                	BigDecimal longitudeb = new BigDecimal(longitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLongitude(longitudeb.toString());
    			} 
                
                String  latitude = getCellValue(row.getCell(11));
                if (ToolUtil.isNotEmpty(latitude)) {
                	BigDecimal latitudeb = new BigDecimal(latitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLatitude(latitudeb.toString());
    			} 
                
                String  kilometer = getCellValue(row.getCell(12));
                if (ToolUtil.isNotEmpty(kilometer)) {
                	BigDecimal kilometerb = new BigDecimal(kilometer).setScale(1,BigDecimal.ROUND_DOWN);
                	bd2.setKilometer(kilometerb.toString());
    			} 
                
                String  lineName = getCellValue(row.getCell(13));
                if (ToolUtil.isNotEmpty(lineName)) {
                	BasicLineResult  basicLineResult = lineMap.get(lineName);
                	if(basicLineResult != null) {
                		bd2.setLineId(Long.parseLong(basicLineResult.getId().toString()));
                		bd2.setLineName(basicLineResult.getLineName());
                	}
    			} 
                
                String  putgoodsNotes = getCellValue(row.getCell(14));
                if (ToolUtil.isNotEmpty(putgoodsNotes)) {
                	if(putgoodsNotes.length()>100) {
        				data.setSuccess(false);
        				data.setMessage("注意事项不得超过100字");
        				return data;
                	}
                	bd.setPutgoodsNotes(putgoodsNotes);
    			} 
                
                bd.setId(basicPutgoodsResult.getId());
                this.save(bd);
                
                bd2.setPutgoodsId(Long.parseLong(bd.getId().toString()));
                BasicAddressResult addressResult = basicAddressService.findBySpec(bd2);
                if (addressResult == null) {
                    if(ToolUtil.isEmpty(bd2.getLongitude())) {
                    	bd2.setLongitude("0");
                    }
                    if(ToolUtil.isEmpty(bd2.getLatitude())) {
                        bd2.setLatitude("0");
                    }
                    bd2.setSwitchWl("1");
                    bd2.setSwitchBj("1500");
                    bd2.setSwitchBj2("2000");
                    basicAddressService.add(bd2);
				} else {
					bd2.setId(addressResult.getId());
					basicAddressService.update(bd2);
				}
			}
        }
		
        data.setSuccess(true);
		return data;
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=280)
	public ResponseData getExceldataupdate(MultipartFile file, BasicPutgoodsParam basicPutgoodsParam, ResponseData data) throws IOException {
		User user = userService.getcurrentUser();
		basicPutgoodsParam.setDeliverId(user.getDeliverId());
		basicPutgoodsParam.setDeptId(user.getDeptId());
		if (basicPutgoodsParam.getPutgoodsCustomerId() == null) {
			data.setSuccess(false);
			data.setMessage("Please Select Customer");
			return data;
		}
		BasicCustomer basicCustomer = basicCustomerService.getById(basicPutgoodsParam.getPutgoodsCustomerId());
		String fileName = file.getOriginalFilename();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Upload file format is incorrect");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

		Map<String, BasicPutgoodsResult> putgoodsMap = new HashMap<>();
		BasicPutgoodsParam hxgoodsp = new BasicPutgoodsParam();
		hxgoodsp.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
		List<BasicPutgoodsResult> hxp = this.findListBySpec(hxgoodsp,null);
		for (BasicPutgoodsResult pr : hxp) {
			putgoodsMap.put(pr.getPutgoodsName(), pr);
		}
		
		Map<String, BasicLineResult> lineMap = new HashMap<>();
		BasicLineParam linep = new BasicLineParam();
		linep.setDeptId(user.getDeptId());
		List<BasicLineResult> lr = basicLineService.findListBySpec(linep,user.getOperateId());
		for (BasicLineResult pr : lr) {
			if(ToolUtil.isNotEmpty(pr.getLineName())) {
				lineMap.put(pr.getLineName(), pr);
			}
		}
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            BasicPutgoodsParam bd = new BasicPutgoodsParam();
            BasicAddressParam bd2 = new BasicAddressParam();
            bd.setDeliverId(basicPutgoodsParam.getDeliverId());
            bd.setDeptId(basicPutgoodsParam.getDeptId());
            bd.setPutgoodsCustomerId(basicPutgoodsParam.getPutgoodsCustomerId());
            bd.setPutgoodsOperateName(basicCustomer.getCustomerName());
            
            String  putgoodsName = getCellValue(row.getCell(0));//单位名称
            if (ToolUtil.isNotEmpty(putgoodsName)) {
            	bd.setPutgoodsName(putgoodsName);
            	bd2.setPutgoodsName(putgoodsName);
			} else {
				data.setSuccess(false);
				data.setMessage("单位名称不得为空");
				return data;
			}
            
            String  unitNumber = getCellValue(row.getCell(1));//单位编号
            if (ToolUtil.isNotEmpty(unitNumber)) {
            	bd.setUnitNumber(unitNumber);
			} 
			BasicPutgoodsResult  basicPutgoodsResult = putgoodsMap.get(putgoodsName);
            if (basicPutgoodsResult != null) {
                String  unitCategory = getCellValue(row.getCell(2));//单位类别
                if (ToolUtil.isNotEmpty(unitCategory)) {
                	bd.setUnitCategory(unitCategory);
    			} 
                
                String  unitType = getCellValue(row.getCell(3));//单位性质
                if (ToolUtil.isNotEmpty(unitType)) {
                	bd.setUnitType(unitType);
    			} 
                
                String  sheng = getCellValue(row.getCell(4));//省
                if (ToolUtil.isNotEmpty(sheng)) {
                	bd2.setSheng(sheng);
    			} 
                
                String  shi = getCellValue(row.getCell(5));//市
                if (ToolUtil.isNotEmpty(shi)) {
                	bd2.setShi(shi);
    			} 
                
                String  qu = getCellValue(row.getCell(6));//区
                if (ToolUtil.isNotEmpty(qu)) {
                	bd2.setQu(qu);
    			} 
                
                String  putgoodsContacts = getCellValue(row.getCell(7));
                if (ToolUtil.isNotEmpty(putgoodsContacts)) {
                	bd2.setContacts(putgoodsContacts);
    			} 
                
                String  putgoodsTel = getCellValue(row.getCell(8));
                if (ToolUtil.isNotEmpty(putgoodsTel)) {
                	bd2.setTel(putgoodsTel);
    			} 
                
                String  putgoodsAddress = getCellValue(row.getCell(9));
                if (ToolUtil.isNotEmpty(putgoodsAddress)) {
                	bd2.setAddress(putgoodsAddress);
    			} 
                
                String  longitude = getCellValue(row.getCell(10));
                if (ToolUtil.isNotEmpty(longitude)) {
                	BigDecimal longitudeb = new BigDecimal(longitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLongitude(longitudeb.toString());
    			} 
                
                String  latitude = getCellValue(row.getCell(11));
                if (ToolUtil.isNotEmpty(latitude)) {
                	BigDecimal latitudeb = new BigDecimal(latitude).setScale(8,BigDecimal.ROUND_DOWN);
                	bd2.setLatitude(latitudeb.toString());
    			} 
                
                String  kilometer = getCellValue(row.getCell(12));
                if (ToolUtil.isNotEmpty(kilometer)) {
                	BigDecimal kilometerb = new BigDecimal(kilometer).setScale(1,BigDecimal.ROUND_DOWN);
                	bd2.setKilometer(kilometerb.toString());
    			} 
                
                String  lineName = getCellValue(row.getCell(13));
                if (ToolUtil.isNotEmpty(lineName)) {
                	BasicLineResult  basicLineResult = lineMap.get(lineName);
                	if(basicLineResult != null) {
                		bd2.setLineId(Long.parseLong(basicLineResult.getId().toString()));
                		bd2.setLineName(basicLineResult.getLineName());
                	}
    			} 
                
                String  putgoodsNotes = getCellValue(row.getCell(14));
                if (ToolUtil.isNotEmpty(putgoodsNotes)) {
                	if(putgoodsNotes.length()>100) {
        				data.setSuccess(false);
        				data.setMessage("注意事项不得超过100字");
        				return data;
                	}
                	bd.setPutgoodsNotes(putgoodsNotes);
    			} 
                
                bd.setId(basicPutgoodsResult.getId());
                this.update(bd);
                
                bd2.setPutgoodsId(Long.parseLong(bd.getId().toString()));
                BasicAddressResult addressResult = basicAddressService.findBySpec(bd2);
                if (addressResult != null) {
					bd2.setId(addressResult.getId());
					basicAddressService.update(bd2);
				}
			}
        }
		
        data.setSuccess(true);
		return data;
	}
	
	@Override
	public BasicPutgoodsResult findCareful(BasicPutgoodsParam param) {
		return this.baseMapper.findCareful(param);
	}

	@Override
	public List<BasicPutgoodsResult> findListBySpecLimit5(BasicPutgoodsParam param, Long operateId) {
		return this.baseMapper.findListBySpecLimit5(param,operateId);
	}

	@Override
	public List<BasicPutgoodsResult> findListBySpecjinweidu(BasicPutgoodsParam param) {
		return this.baseMapper.findListBySpecjinweidu(param);
	}

    @Override
    public List<BasicPutgoodsResult> noBindList(BasicPutgoods paramCondition, Long operateId) {
        return this.baseMapper.noBindList(paramCondition, operateId);
    }

    @Override
    public List<BasicPutgoodsResult> bindList(BasicPutgoods paramCondition, Long operateId) {
        return this.baseMapper.bindList(paramCondition, operateId);
    }

	@Override
	public Workbook exportToExcel(BasicPutgoodsParam basicPutgoodsParam, String condition) {
	    //This is the header
	    String[] arr = {"Unit Name","Type","Address","Province","City","District"
	    		,"Contact Person","Phone","Longitude","Latitude"
	    		,"Kilometers","Route","Delivery Notes"};
	    //This is the specific data
    List<List<String>> list = new ArrayList<>();

    	User user = userService.getcurrentUser();
	    List<BasicPutgoodsResult> datalist = this.exportToExcel(basicPutgoodsParam,condition,user.getDeptId(),user.getOperateId());
	    for (BasicPutgoodsResult r : datalist) {
		    List<String> list1 = new ArrayList<String>();
		    list1.add(r.getPutgoodsName());
		    list1.add(r.getUnitType());
		    list1.add(r.getSetLocation());
		    list1.add(r.getSheng());
		    list1.add(r.getShi());
		    list1.add(r.getQu());
		    
		    list1.add(r.getSetPeople());
		    list1.add(r.getSetTel());
		    list1.add(r.getLongitude());
		    list1.add(r.getLatitude());
		    
		    list1.add(r.getKilometer());
		    list1.add(r.getLineName());
		    list1.add(r.getPutgoodsNotes());
		    list.add(list1);
		}
	    return ExcelWrite.writeToExcelByList(arr, list);
	}

	@Override
	public List<BasicPutgoodsResult> exportToExcel(BasicPutgoodsParam param, String condition, Long deptId,
			Long operateId) {
		return this.baseMapper.exportToExcel(param,condition,deptId,operateId);
	}

    @Override
    public BasicPutgoodsResult findByName(String name, Long putgoodsCustomerId) {
        return this.baseMapper.findByName(name,putgoodsCustomerId);
    }

    @Override
    public LayuiPageInfo getStoreByWarehouseId(String warehouseId) {

        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getStoreByWarehouseId(pageContext, warehouseId);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public void unBindStoreByWarehouseId(String storeId, String warehouseId) {
        this.baseMapper.unBindStoreByWarehouseId(storeId,warehouseId);
    }
}
